#include "Socket.hpp"
#include "Common.hpp"
#include "Protocol.hpp"

using namespace SocketModule;

void GetDataFromStdin(int* x,int* y,char* oper)
{
    std::cout << "Please Enter x: ";
    std::cin >> *x;
    std::cout << "Please Enter y: ";
    std::cin >> *y;
    std::cout << "Please Enter oper: ";
    std::cin >> *oper;
}

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        std::cerr << "Usage:" << argv[0] << " server_ip server_port" << std::endl;
        exit(USAGE_ERR);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    std::shared_ptr<Socket> client = std::make_shared<TcpSocket>();
    client->BuildTcpClientSocketMethod();

    if(client->Connect(server_ip,server_port) != 0)
    {
        LOG(LogLevel::FATAL) << "connect error";
        exit(CONNECT_ERR);
    }

    //通过协议构造请求
    std::unique_ptr<Protocol> protocol = std::make_unique<Protocol>();
    std::string buffer_queue;//客户端也该有该队列

    while(true)
    {
        //1.从标准输入中获取数据
        int x,y;
        char oper;
        GetDataFromStdin(&x,&y,&oper);

        //2.构造请求
        std::string send_json_req = protocol->BuildRequestString(x,y,oper);

        //3.发送请求
        client->Send(send_json_req);
        //std::cout<<"发送的请求："<<send_json_req<<std::endl;

        //4.接收应答,结果写到res中
        Response res;
        bool r = protocol->GetResponse(client,buffer_queue,&res);

        //5.显示结果
        res.ShowResult();
    }
    
    client->Close();
    return 0;
}